import { Component, OnInit } from '@angular/core';
import {CartService} from '../service/cart.service';
import {CartResult} from '../shared/cartResult.interface';
import {Cart1Service} from "../service/cart.service";

@Component({
  selector: 'app-cart',
  templateUrl: './cart.component.html',
  styleUrls: ['./cart.component.less']
})
export class CartComponent implements OnInit {
  logined;
  carts: CartResult= {
    cart: [],
    totalNumber: 0,
    totalPrice: 0,
    selectedTotalNumber: 0,
    selectedTotalPrice: 0,
    allS: true
  };
  constructor(private cartService: Cart1Service) { }

  ngOnInit() {
    // this.logined = this.cartService.getToken();
    // if (this.logined) {
    //   this.getCarts();
    // } else {
    //   this.getLocalCarts();
    // }
  }
  // 获取本地购物车数据
  getLocalCarts() {
    this.carts = this.cartService.localGetCart();
    this.cartService.cartChanged.subscribe(
      (result: CartResult) => {
        this.carts = result;
      }
    );
  }
  // 获取线上购物车数据
  getCarts() {
    this.cartService.getCartList().subscribe(
      (products) => {
        if (products.cart) {
          this.carts = products;
          this.carts.cart = products.cart;
        }
      }
    );
  }
  quantityChanged(number: number, id: number) {
    const update = {
      quantity: number,
      goodsId: id
    };
    if (this.logined) {
      if (number <= 0) {
        this.cartService.deleteProduct(id)
          .subscribe(
            (result) => {
              if (result.code === 1) {
                this.getCarts();
              }
            }
          );
      }else {
        this.cartService.updateCart(update)
          .subscribe(
            (result) => {
              if (result.code === 1) {
                this.getCarts();
              }
            }
          );
      }
    } else {
      this.cartService.localChangeQuantity(number, id);
    }
  }
  minus(quantity: number, id: number) {
    const q = quantity - 1;
    this.quantityChanged(q, id);
  }
  plus(quantity: number, id: number) {
    const q = quantity + 1;
    this.quantityChanged(q, id);
  }
  delete(id: number) {
    if (this.logined) {
      this.cartService.deleteProduct(id)
        .subscribe(
          (result) => {
            if (result.code === 1) {
              this.getCarts();
            }
          }
        );
    } else {
      this.cartService.localDeleteProduct(id);
    }
  }
  changeSelected(p, changed) {
    this.cartService.selectedProduct(p, changed);
  }
  onSelectedAll() {
    this.cartService.selectedAll();
  }
}
